package com.it.sun.learning001.base;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @ClassName com.it.sun.learning001.base.EnhanceCar
 * @Author sunmannian
 * @Date 2021/6/23 13:52
 * @Version V1.0
 * Description  <请输入一句话描述该类功能>
 * Copyright (C) 北京中电兴发科技有限公司  since 2021/6/23
 */
public class EnhanceCar implements MethodInterceptor {

	private Car car;

	public EnhanceCar(Car car) {
		this.car = car;
	}

	@Override
	public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
		// 只增强drive方法
		if (method.equals(Car.class.getMethod("drive"))) {
			System.err.println("开始无人驾驶");
		}
		return method.invoke(car, objects);
	}

	public Object getEnhancerCar() {
		Enhancer enhancer = new Enhancer();
		enhancer.setSuperclass(car.getClass());
		enhancer.setCallback(this);
		return enhancer.create();
	}
}
